<template>
  <div v-loading="loading" class="energy-consume">
    <div class="overview-wrap">
      <modelTitle :title="'能源用量总览'" />
      <div class="amount-wrap">
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/coal.png" class="img" alt="图片" />
            <span class="text">等价折标煤</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.scoalEquivalent || "-" }}</span
            ><span class="unit">tce</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/coal.png" class="img" alt="图片" />
            <span class="text">当量折标煤</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.scoalCalorific || "-" }}</span
            ><span class="unit">tce</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/co2.png" class="img" alt="图片" />
            <span class="text">碳排放</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.ecarbon || "-" }}</span
            ><span class="unit">tCO2e</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/elec.png" class="img" alt="图片" />
            <span class="text">电</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.electricity || "-" }}</span
            ><span class="unit">kWh</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/water.png" class="img" alt="图片" />
            <span class="text">水</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.water || "-" }}</span
            ><span class="unit">m³</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/ng.png" class="img" alt="图片" />
            <span class="text">天然气</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.ng || "-" }}</span
            ><span class="unit">Nm³</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/steam.png" class="img" alt="图片" />
            <div class="text-wrap" @click="handleSwitch('steam')">
              <span class="text">蒸汽</span><px-icon><Switch size="small" /></px-icon>
            </div>
          </div>
          <div v-if="steamBool" class="item-btm">
            <span class="num">{{ dataObj?.steamT || "-" }}</span
            ><span class="unit">t</span>
          </div>
          <div v-else class="item-btm">
            <span class="num">{{ dataObj?.steamGJ || "-" }}</span
            ><span class="unit">GJ</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/hot_water.png" class="img" alt="图片" />
            <div class="text-wrap" @click="handleSwitch('hot')">
              <span class="text">热水</span><px-icon><Switch size="small" /></px-icon>
            </div>
          </div>
          <div v-if="hotBool" class="item-btm">
            <span class="num">{{ dataObj?.hotGJ || "-" }}</span
            ><span class="unit">GJ</span>
          </div>
          <div v-else class="item-btm">
            <span class="num">{{ dataObj?.hotT || "-" }}</span
            ><span class="unit">t</span>
          </div>
        </div>
        <div class="item">
          <div class="item-top">
            <img src="@/assets/images/energy/supplyOverview/gas.png" class="img" alt="图片" />
            <span class="text">大宗气</span>
          </div>
          <div class="item-btm">
            <span class="num">{{ dataObj?.gas || "-" }}</span
            ><span class="unit">Nm³</span>
          </div>
        </div>
      </div>
    </div>
    <div class="chart-wrap">
      <px-row :gutter="16" class="mg-bt-10">
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'折标煤趋势'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'coalRef')" />
            <div ref="coalRef" class="chart-item" />
          </div>
        </px-col>
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'碳排放趋势'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'co2Ref')" />
            <div ref="co2Ref" class="chart-item" />
          </div>
        </px-col>
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'电'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'eleRef')" />
            <div ref="eleRef" class="chart-item" />
          </div>
        </px-col>
      </px-row>
      <px-row :gutter="16" class="mg-bt-10">
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'自来水'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'waterRef')" />
            <div ref="waterRef" class="chart-item" />
          </div>
        </px-col>
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'再生水'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'recycledWaterRef')" />
            <div ref="recycledWaterRef" class="chart-item" />
          </div>
        </px-col>
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'天然气'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'ngRef')" />
            <div ref="ngRef" class="chart-item" />
          </div>
        </px-col>
      </px-row>
      <px-row :gutter="16">
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'蒸汽'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'steamRef')" />
            <div ref="steamRef" class="chart-item" />
          </div>
        </px-col>
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'热水'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'hotWaterRef')" />
            <div ref="hotWaterRef" class="chart-item" />
          </div>
        </px-col>
        <px-col :span="8">
          <div class="black">
            <modelTitle :title="'大宗气'" />
            <btnImageAndData class="btn" :exportData="Boolean(false)" @exportChange="val => handlerExport(val, 'gasRef')" />
            <div ref="gasRef" class="chart-item" />
          </div>
        </px-col>
      </px-row>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, toRefs, onMounted, computed, watch, nextTick, getCurrentInstance } from "vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import btnImageAndData from "@/views/common/energy/components/btnImageAndData/index.vue";
import * as echarts from "echarts";
import { getSupplySummaryAPI } from "@/api/energy/supplyOverview";

const { proxy } = getCurrentInstance();

const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  activeName: {
    type: String,
    default: () => ""
  }
});

const coalRef = ref();
const co2Ref = ref();
const eleRef = ref();
const waterRef = ref();
const recycledWaterRef = ref();
const ngRef = ref();
const steamRef = ref();
const hotWaterRef = ref();
const gasRef = ref();

const state = reactive({
  loading: false,
  steamBool: true, // 蒸汽的切换
  hotBool: true, // 热水的切换
  dataObj: {
    scoal: "", //折标煤量
    ecarbon: "", // 碳排放量
    electricity: "", // 	电量
    water: "", // 水量
    ng: "", // 天然气量
    steamT: "", // 蒸汽量（t）
    steamGJ: "", // 蒸汽量（GJ）
    hotT: "", // 热水量（t）
    hotGJ: "", // 热水量（GJ）
    gas: "", // 大宗气量
    scoalTrend: {
      xaxis: [],
      yaxis: []
    },
    ecarbonTrend: {
      xaxis: [],
      yaxis: []
    },
    electricityTrend: {
      xaxis: [],
      yaxis: []
    },
    runningTrend: {
      xaxis: [],
      yaxis: []
    },
    reclaimTrend: {
      xaxis: [],
      yaxis: []
    },
    ngTrend: {
      xaxis: [],
      yaxis: []
    },
    steamTTrend: {
      xaxis: [],
      yaxis: []
    },
    steamGJTrend: {
      xaxis: [],
      yaxis: []
    },
    hotTTrend: {
      xaxis: [],
      yaxis: []
    },
    hotGJTrend: {
      xaxis: [],
      yaxis: []
    },
    gasTrend: {
      xaxis: [],
      yaxis: []
    }
  }
});
const { loading, dataObj, steamBool, hotBool } = toRefs(state);
const queryParams = computed(() => props.params);

onMounted(() => {
  getData();
});
watch(
  () => props.params,
  val => {
    console.log("val", val);
    // if (val.startTime && val.endTime) {
    //   getData();
    // }
  },
  { deep: true }
);
// 获取总览数据
const getData = async () => {
  try {
    state.loading = true;
    const { startDate, endDate, dimension } = getParams();

    const params = {
      factoryId: "",
      facCode: "",
      dimension: dimension || "",
      startDate: startDate || "",
      endDate: endDate || ""
    };
    if (startDate && endDate) {
      const res = await getSupplySummaryAPI(params);
      if (res) {
        state.dataObj = res;
      }
      nextTick(() => {
        res?.scoalTrend ? drawBarChart(coalRef.value, res?.scoalTrend, 0, "coalRef") : "";
        res?.ecarbonTrend ? drawBarChart(co2Ref.value, res?.ecarbonTrend, 1, "co2Ref") : "";
        res?.electricityTrend ? drawBarChart(eleRef.value, res?.electricityTrend, 2, "eleRef") : "";
        res?.runningTrend ? drawBarChart(waterRef.value, res?.runningTrend, 3, "waterRef") : "";
        res?.reclaimTrend ? drawBarChart(recycledWaterRef.value, res?.reclaimTrend, 4, "recycledWaterRef") : "";
        res?.ngTrend ? drawBarChart(ngRef.value, res?.ngTrend, 5, "ngRef") : "";
        res?.steamTTrend ? drawBarChart(steamRef.value, res?.steamTTrend, 6, "steamRef") : "";
        res?.hotGJTrend ? drawBarChart(hotWaterRef.value, res?.hotGJTrend, 7, "hotWaterRef") : "";
        res?.gasTrend ? drawBarChart(gasRef.value, res?.gasTrend, 8, "gasRef") : "";
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};
let chartObj = {};
// 画柱状图
const drawBarChart = (dom, obj, args, args2) => {
  if (dom) {
    let colors = ["#3B82F6 ", "#39C670", "#F15645", "#40D3FF", "#2D52DA", "#FFC53D", "#13C2C2", "#8573E2", "#FFEC58"];
    let seriesData = obj?.yaxis?.map(i => {
      if (args === 0) {
        return {
          name: i.name,
          stack: "Total",
          type: "bar",
          data: i.value
        };
      } else {
        return {
          name: i.name,
          stack: "Total",
          type: "bar",
          data: i.value,
          itemStyle: {
            color: colors[args] // 设置柱子颜色为天蓝色
          }
        };
      }
    });
    let options = {
      // toolbox: {
      //   show: true,
      //   feature: {
      //     saveAsImage: {
      //       title: "点击保存为图片"
      //     }
      //   }
      // },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          let total = 0;
          // 蒸汽/热水块，只需要合计GJ类型的数据
          let paramsGj = params.filter(item => item.seriesName.includes("GJ"));
          if (paramsGj.length) {
            total = paramsGj.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          } else {
            total = params.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          }
          total = total.toFixed(2);
          // 生成内容
          let html = `<div>${params[0].name}</div>`;
          params.forEach(item => {
            html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
          });
          if (args2 === "coalRef") {
            html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
          }
          return html;
        }
      },
      legend: {},
      grid: {
        bottom: "20%",
        right: "5%",
        top: "25%"
      },
      xAxis: {
        type: "category",
        data: obj?.xaxis || []
      },
      yAxis: {
        type: "value",
        name: "单位：" + obj?.yaxis[0]?.unit || "", // 为 Y 轴添加文本
        // nameLocation: "middle", // 文本位置，可选值：'start'、'middle'、'end'
        // nameGap: 70, // 文本与坐标轴的距离
        axisLabel: {
          formatter: function (value) {
            if (value >= 1e12) {
              return (value / 1e12).toFixed(1) + "T"; // 万亿
            } else if (value >= 1e9) {
              return (value / 1e9).toFixed(1) + "B"; // 十亿
            } else if (value >= 1e6) {
              return (value / 1e6).toFixed(1) + "M"; // 百万
            } else if (value >= 1e3) {
              return (value / 1e3).toFixed(1) + "K"; // 千
            }
            return value;
          }
        }
      },
      series: seriesData
    };
    let myChart = echarts.init(dom);
    chartObj[args2] = myChart;
    myChart.clear();
    myChart.setOption(options);
  }
};

// 获取参数
const getParams = () => {
  let timeType = queryParams.value.queryTimeGranularity;
  let startDate = queryParams.value.startTime || "";
  let endDate = queryParams.value.endTime || "";

  let timeObj = {
    Hourly: "HOUR",
    Daily: "DAY",
    Monthly: "MONTH",
    Yearly: "YEAR"
  };
  let dimension = timeObj[timeType] || MONTH;
  return {
    startDate,
    endDate,
    dimension
  };
};
// 蒸汽和热水的切换
const handleSwitch = val => {
  // 蒸汽
  if (val === "steam") {
    state.steamBool = !state.steamBool;
    if (state.steamBool) {
      state.dataObj?.steamTTrend ? drawBarChart(steamRef.value, state.dataObj?.steamTTrend, 6, "steamRef") : "";
    } else {
      state.dataObj?.steamGJTrend ? drawBarChart(steamRef.value, state.dataObj?.steamGJTrend, 6, "steamRef") : "";
    }
  }
  // 热水
  if (val === "hot") {
    state.hotBool = !state.hotBool;
    if (state.hotBool) {
      state.dataObj?.hotGJTrend ? drawBarChart(hotWaterRef.value, state.dataObj?.hotGJTrend, 7, "hotWaterRef") : "";
    } else {
      state.dataObj?.hotTTrend ? drawBarChart(hotWaterRef.value, state.dataObj?.hotTTrend, 7, "hotWaterRef") : "";
    }
  }
};

// 导出方法
const handlerExport = (val1, val2) => {
  let myChart = chartObj[val2];
  if (!myChart) return;
  // 获取Base64图片数据
  const imgUrl = myChart.getDataURL({
    type: "png",
    pixelRatio: 2,
    backgroundColor: "#fff"
  });
  // 创建并触发下载链接
  const link = document.createElement("a");
  link.href = imgUrl;
  link.download = "chart.png";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style lang="scss" scoped>
.energy-consume {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.btn {
  position: absolute;
  top: 10px;
  right: 16px;
}

.overview-wrap {
  padding: 12px 16px;
  margin-bottom: 16px;
  background-color: #fff;
  border-radius: 4px;

  .amount-wrap {
    display: flex;
    justify-content: space-around;
    margin-top: 16px;

    .item {
      .item-top {
        display: flex;
        align-items: center;

        .img {
          width: 32px;
          height: 32px;
          margin-right: 8px;
        }

        .text-wrap {
          display: flex;
          align-items: center;
          margin-left: 8px;

          .text {
            margin-right: 4px;
          }
        }

        .text {
          font-size: 14px;
          font-weight: 400;
        }
      }

      .item-btm {
        display: flex;
        align-items: flex-end;
        justify-content: space-around;

        .num {
          font-size: 16px;
          font-weight: 500;
        }

        .unit {
          margin-left: 4px;
          font-size: 14px;
          font-weight: 400;
        }
      }
    }
  }
}

.chart-wrap {
  display: flex;
  flex: 1;
  flex-direction: column;

  .mg-bt-10 {
    margin-bottom: 10px;
  }

  .px-row {
    flex: 1;

    .px-col {
      height: 100%;

      .black {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
        padding: 10px 16px 0;
        background-color: #fff;
        border-radius: 4px;

        :deep(.model-title-com) {
          height: 24px;

          .title-text {
            .re-text-tooltip-text {
              font-size: 14px;
            }
          }
        }

        .chart-item {
          flex: 1;
          margin-top: 5px;
        }
      }
    }
  }
}
</style>
